package com.jinshan.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.jinshan.edu.entity.EduSubject;
import com.jinshan.edu.entity.SubjectLevelHead;
import com.jinshan.edu.service.EduSubjectService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class SubjectAnalysisListener extends AnalysisEventListener<SubjectLevelHead> {
    @Resource
    private EduSubjectService eduSubjectService;

    @Override
    public void invoke(SubjectLevelHead data, AnalysisContext context) {
        String firstLevelTitleName = data.getFirstLevelTitleName();
        String secondLevelTitleName = data.getSecondLevelTitleName();
        // 通过一级分类的parentId和title查询数据库是否有该分类, 如果没有, 向里面添加, 如果有就不用
        EduSubject eduSubjectParent = eduSubjectService.querySubjectByTitleAndParentId(firstLevelTitleName, "0");
        if (eduSubjectParent == null) {
            // 如果没有查到, 就向数据库中添加
            eduSubjectParent = new EduSubject();
            eduSubjectParent.setParentId("0");
            eduSubjectParent.setTitle(firstLevelTitleName);
            eduSubjectService.addEduSubject(eduSubjectParent);
        }

        // 通过二级分类的title和parentId查询数据是否存在, 如果存在, 就不做任何操作, 如果不存在, 就添加数据
        EduSubject eduSubjectChild = eduSubjectService.querySubjectByTitleAndParentId(secondLevelTitleName, eduSubjectParent.getId());
        if (eduSubjectChild == null) {
            eduSubjectChild = new EduSubject();
            eduSubjectChild.setTitle(secondLevelTitleName);
            eduSubjectChild.setParentId(eduSubjectParent.getId());
            eduSubjectService.addEduSubject(eduSubjectChild);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}
